const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const dayjs = require('dayjs');
const ResponseDTO = require('./res');
// 情侣关系表
const COUPLE = 'cloud_couples';
const USER = 'edu-cloud-users';
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 获取用户ID
  let userId = event.userId || wxContext.OPENID;
  // 获取传入情侣ID
  let coupleId = event.coupleId;
  if (userId == coupleId){
    return ResponseDTO.wrap(403,"不可以绑定自己");
  }
  // 获取记录
  let queryRes = await db.collection(COUPLE).where({
    userId
  }).get();
  if (queryRes.data.length != 0) {
    return ResponseDTO.wrap(403, "请勿重复绑定!")
  }
  // 获取情侣记录
  let coupleRes = await db.collection(COUPLE).where({
    userId: coupleId
  }).get();
  if (coupleRes.data.length != 0) {
    return ResponseDTO.wrap(403, "对方已绑定情侣!");
  }
  await db.collection(COUPLE).add({
    data: {
      userId,
      coupleId,
      bindDate: dayjs().format('YYYY-MM-DD')
    }
  })
  //逆转调用 -- bug fix 无限递归
  await db.collection(COUPLE).add({
    data: {
      userId:coupleId,
      coupleId:userId,
      bindDate: dayjs().format('YYYY-MM-DD')
    }
  })
  return ResponseDTO.succMsg("绑定成功");
}